package com.km.wskj.itmonitor.pager.monitor.server;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fingdo.statelayout.StateLayout;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.AlarmListType;
import com.km.wskj.itmonitor.model.Server;
import com.km.wskj.itmonitor.model.Type;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.pager.monitor.database.domain.DbMsg;
import com.km.wskj.itmonitor.utils.FloatUtils;
import com.km.wskj.itmonitor.utils.StatusBarCompat;
import com.km.wskj.itmonitor.utils.TimeUtils;
import com.zxl.zxlapplibrary.adapter.BaseAdapterHelper;
import com.zxl.zxlapplibrary.global.Constant;
import com.zxl.zxlapplibrary.http.callback.StringCallback;
import com.zxl.zxlapplibrary.util.LogUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;

/**
 * @author by Xianling.Zhou on 2017/2/9.
 */

//服务器列表页面
public class ServerListActivity extends LActivity implements StateLayout.OnViewRefreshListener {

    private static final String TAG = "ServerListActivity";
    //ui
    @BindView(R.id.zlv_server_type)
    ZrcListView mZrcListView;
    @BindView(R.id.sp_server_type)
    Spinner mSpinner;
    @BindView(R.id.state_layout)
    StateLayout mStateLayout;

    MyAdapter mAdapter;
    int pageIndex;
    int lastUpdateNum;
    List<Server> serverList;
    String serverType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_server_list);
        ButterKnife.bind(this);
        serverList = new ArrayList<>();
        mStateLayout.setRefreshListener(this);
        initSpinner();
    }

    private void initData() {
        pdc.serverList(HTTP_TASK_TAG, 1, Constant.PageListSize, serverType, new ZxlGenericsCallback<List<Server>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                mStateLayout.showErrorView();
            }

            @Override
            public void onResponse(List<Server> servers, int i) {
                if (servers.size() == 0)
                    mZrcListView.setRefreshSuccess("暂无数据");

                serverList = servers;
                lastUpdateNum = servers.size();
                pageIndex = 1;
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setRefreshSuccess();
                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();
            }
        });
        initPullToRefresh();
    }

    private void initPullToRefresh() {
        //配置listview
        ColorDrawable line = new ColorDrawable(getResources().getColor(R.color.color_line));
        mZrcListView.setDivider(line);
        mZrcListView.setDividerHeight(1);

        //设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(context);
        header.setTextColor(ContextCompat.getColor(context, R.color.text_gray));
        header.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setHeadable(header);

        //设置加载更多的样式（可选）
        SimpleFooter footer = new SimpleFooter(context);
        footer.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setFootable(footer);

        // 设置列表项出现动画（可选）
        //zListView.setItemAnimForTopIn(R.anim.topitem_in);
        mZrcListView.setItemAnimForBottomIn(R.anim.bottomitem_in);

        // 下拉刷新事件回调（可选）
        mZrcListView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onRefresh();
            }
        });

        // 加载更多事件回调（可选）
        mZrcListView.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onLoadMore();
            }
        });

        // 项目选中
        mZrcListView.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                Server server = (Server) parent.getItemAtPosition(position);
                Intent intent = new Intent(context, ServerDetailActivity.class);
                intent.putExtra("id", server.id);
                intent.putExtra("ip", server.ip);
                startActivity(intent);
            }
        });

        mAdapter = new MyAdapter();
        mZrcListView.setAdapter(mAdapter);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mStateLayout.showContentView();
            }
        }, 500);
    }

    private void onRefresh() {
        pdc.serverList(HTTP_TASK_TAG, 1, Constant.PageListSize, serverType, new ZxlGenericsCallback<List<Server>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e("error", e);
                mStateLayout.showErrorView();
            }

            @Override
            public void onResponse(List<Server> servers, int i) {
                if (servers.size() == 0)
                    mZrcListView.setRefreshSuccess("暂无数据");

                serverList = servers;
                lastUpdateNum = servers.size();
                pageIndex = 1;
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setRefreshSuccess();

                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();
            }
        });
    }

    private void onLoadMore() {
        pdc.serverList(HTTP_TASK_TAG, pageIndex + 1, Constant.PageListSize, serverType, new ZxlGenericsCallback<List<Server>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(List<Server> servers, int i) {
                lastUpdateNum = servers.size();
                if (servers.size() > 0) {
                    serverList.addAll(servers);
                    pageIndex++;
                }
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setLoadMoreSuccess();
                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();

            }
        });

    }

    private boolean haveMore() {
        return lastUpdateNum > 0;
    }

    @Override
    public void refreshClick() {
        initSpinner();
    }

    @Override
    public void loginClick() {

    }

    /**
     * 适配器
     */
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (serverList == null) {
                return 0;
            }
            return serverList.size();
        }

        @Override
        public Object getItem(int position) {
            Server item = serverList.get(position);
            return item;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            return 1;
        }

        @Override
        public int getItemViewType(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final BaseAdapterHelper helper = BaseAdapterHelper.get(context, convertView, parent, R.layout.item_monitor_list);
            Server item = serverList.get(position);
            helper.setText(R.id.tv_item_name, item.serverName + "(" + item.serverTypeName + ")");
            helper.setText(R.id.tv_item_ip, item.ip);

            String distanceTime = TimeUtils.getDistanceTime(item.osStartTime, TimeUtils.DateToString(new Date()));
            helper.setText(R.id.tv_item_runTime, distanceTime);

            //运行状态//1正常 2告警 3故障
            switch (item.status) {
                case 1:
                    helper.setImageResource(R.id.iv_item_state, R.mipmap.icon_server_green);
                    break;
                case 2:
                    helper.setImageResource(R.id.iv_item_state, R.mipmap.icon_server_orange);
                    break;
                case 3:
                    helper.setImageResource(R.id.iv_item_state, R.mipmap.icon_server_red);
                    break;
            }
            return helper.getView();
        }
    }

    /**
     * 初始化下拉菜单
     */
    private void initSpinner() {
        mStateLayout.showLoadingView();
        pdc.serverTypeList(HTTP_TASK_TAG, new ZxlGenericsCallback<List<Type>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                mStateLayout.showErrorView();
            }

            @Override
            public void onResponse(List<Type> types, int i) {

                Type t = new Type();
                t.codeName = "全部";
                t.id = "";

                List<Type> mDatas = new ArrayList<Type>();
                mDatas.add(t);
                mDatas.addAll(types);

                //适配器
                ArrayAdapter<Type> mArrayAdapter = new ArrayAdapter<>(context,
                        android.R.layout.simple_spinner_item, mDatas);
                //设置样式
                mArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                //加载适配器
                mSpinner.setAdapter(mArrayAdapter);
                mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                        Type type = (Type) adapterView.getItemAtPosition(i);
                        /**
                         * 设置spinner字体样式
                         */
                        TextView tv = (TextView) view;
                        tv.setTextColor(getResources().getColor(R.color.white));    //设置颜色
                        tv.setTextSize(16.0f);    //设置大小
                        tv.setGravity(Gravity.CENTER_HORIZONTAL);   //设置居中
                        serverType = type.id;

                        initData();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> adapterView) {

                    }
                });
            }
        });


    }

    //点击事件
    @OnClick({R.id.iv_server_back, R.id.tv_server_right})
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.iv_server_back:
                finish();
                break;
            case R.id.tv_server_right:
                openIntent(ServerStatisticsActivity.class, true);
                break;
        }
    }
}
